import * as Cesium from 'cesium'

import BaiduMercatorTilingScheme from './BaiduMercatorTilingScheme'

/**
 * 百度地图影像提供者类，用于加载百度地图瓦片数据
 * @class BaiduImageryProvider
 * @extends Cesium.UrlTemplateImageryProvider
 * @example
 *  new Cesium.ProviderViewModel({
        name: "百度地图",
        iconUrl: Cesium.buildModuleUrl('Widgets/Images/ImageryProviders/naturalEarthII.png'),
        tooltip: "百度地图",
        creationFunction: () => {
          return new BaiduImageryProvider({
            url: "https://maponline{s}.bdimg.com/tile/?qt=vtile&x={x}&y={y}&z={z}&styles=pl&scaler=2&udt=&from=jsapi2_0",
            subdomains: ["1", "2", "3"],
            maximumLevel: 18
          })
        }
      })
        name: "百度地图",
        iconUrl: Cesium.buildModuleUrl('Widgets/Images/ImageryProviders/naturalEarthII.png'),
        tooltip: "百度地图",
        creationFunction: () => {
          return new BaiduImageryProvider({
            url: "https://maponline{s}.bdimg.com/tile/?qt=vtile&x={x}&y={y}&z={z}&styles=pl&scaler=2&udt=&from=jsapi2_0",
            subdomains: ["1", "2", "3"],
            maximumLevel: 18
          })
        }
      })
 */
/**
 * @classdesc 百度地图影像提供者类，用于加载百度地图瓦片数据
 */
class BaiduImageryProvider extends Cesium.UrlTemplateImageryProvider {
    /**
     * 地图可视范围
     * @type {Cesium.Rectangle}
     * @private
     */
    _rectangle
    
    /**
     * 瓦片请求URL模板
     * @type {string}
     * @private
     */
    _url
    
    /**
     * 子域名数组
     * @type {Array<string>}
     * @private
     */
    _subdomains
    
    /**
     * 构造函数
     * @param {Object} options - 配置参数对象
     * @param {string} options.url - 瓦片URL模板，包含{x}, {y}, {z}, {s}等占位符
     * @param {Array<string>} [options.subdomains=[]] - 子域名数组，用于负载均衡
     * @param {number} [options.maximumLevel=18] - 最大缩放级别
     * @param {Cesium.Credit} [options.credit] - 数据源版权信息
     */
    constructor(options) {
        let resolutions = []
        for (let i = 0; i < 19; i++) {
            resolutions[i] = 256 * Math.pow(2, 18 - i)
        }
        options['tilingScheme'] = new BaiduMercatorTilingScheme({
            resolutions,
            rectangleSouthwestInMeters: new Cesium.Cartesian2(-20037726.37, -12474104.17),
            rectangleNortheastInMeters: new Cesium.Cartesian2(20037726.37, 12474104.17),
        })
        options['maximumLevel'] = 18
        super(options)
        this._rectangle = this.tilingScheme.rectangle
        this._url = options.url
        this._subdomains = options.subdomains || []
    }

    /**
     * 请求指定的瓦片图像
     * @param {number} x - 瓦片X坐标
     * @param {number} y - 瓦片Y坐标
     * @param {number} level - 缩放级别
     * @param {Request} request - 请求对象
     * @returns {Promise<HTMLImageElement|HTMLCanvasElement>} 瓦片图像的Promise
     */
    requestImage(x, y, level, request) {
        let url = this._url.replace('{x}', String(x)).replace('{y}', String(-y)).replace('{z}', level);
        if (this._subdomains.length > 0) {
            let subdomain = this._subdomains[Math.floor(Math.random() * this._subdomains.length)]
            url = url.replace('{s}', subdomain)
        }
        return Cesium.ImageryProvider.loadImage(this, url)?.then((image) => {
            if (!image) {
                throw new Error('Loaded image is undefined');
            }
            // 返回加载的图像
            return image;
            throw new Error('Loaded image is not of ImageryTypes');
        });
    }
}

export default BaiduImageryProvider